// pages/drivingSchool/drivingSchool.js
var fileData = require('../../utils/data.js');
var QQMapWX = require('../../lib/qqmap-wx-jssdk.min.js');
Page({
  data: {
    tabsData: fileData.getCoachNavData(),
    evaluateData: fileData.evaluateData(),
    // slideTabsData: fileData.slideTabsData(),
    currentType: 0,
    scrollTp: 0,
    scrollHeight: 0,
    curNavId: 1,
    modalCtrl: 'hidden',
    drivingSchoolName: '',
    drivingSchoolName2: '',
    briefIntroduction: '',
    address: '',
    place: '',
    distance: 0,
    grade: '',
    score: 0,
    titlePic: '',
    schoolName: '',
    classesList: [],
    attention: false,
    schoolId: '', 
    lifePicsLength: 0,
    workPicsLength: 0,
    totalPicsLength: 0, 
    branchCoachList: [],
    headSchoolId: '',
    studentTotal: 0,
    recordsStudentList: [],
    studentListLength: 0,
    pics: [],
    lat2: '',
    lng2: '',
    allTotal: 0,
    goodTotal: 0,
    middleTotal: 0,
    lowTotal: 0,
    allArr: [],
    goodArr: [],
    middleArr: [],
    lowArr: [],
  },

  onLoad: function (options) {
    console.log(options);
    //获取分校学员列表
    this.getStudentListPromise(1, 10, options.tid).then(res => {
      console.log(res);
      if(res.data.code == 0 && res.data.message == "成功"){
        let _arr = [];
        let dataArr = res.data.data.records;
        //处理空头像
        let avatarUrlIndex = dataArr.findIndex(v =>{
          return v.avatarUrl == null
        })
        console.log(avatarUrlIndex);
        if (avatarUrlIndex != -1){
          dataArr.splice(avatarUrlIndex, 1);
        }
        console.log(dataArr);
        if (dataArr.length == 1) {
          for (let i = 0; i < 1; i++) {
            _arr.push(dataArr[i]);
          }
        } else if (dataArr.length == 2) {
          for (let i = 0; i < 2; i++) {
            _arr.push(dataArr[i]);
          }
        } else if (dataArr.length >= 3 && dataArr.length < 10000) {
          for (let i = 0; i < 3; i++) {
            _arr.push(dataArr[i]);
          }
        } 
        this.setData({
          studentTotal: res.data.data.total,
          recordsStudentList: _arr,
          studentListLength: _arr.length,
        })
      }
    }).catch(err => {
      console.warn(err);
    })
    //获取分校教练列表
    // this.getBranchListPromise(options.tid).then(res => {
    //   if(res.data.code == 0 && res.data.message == "成功"){
    //     const newArr = res.data.data;
    //     for(let i of newArr){
    //       i.score = i.score.toFixed(1);
    //     }
    //     const newArr1 = [];
    //     for(let i = 0 ; i < 3 ; i++ ){
    //       if(newArr[i]){
    //         newArr1.push(newArr[i]);
    //       }
    //     }
    //     this.setData({
    //       branchCoachList: newArr1,
    //     })
    //   }
    // }).catch(err=>{
    //   console.warn(err);
    // })
    this.setData({
      schoolId: options.tid,
    })
    this.getAttentionState(options.tid).then(res=>{
      console.log(res);
      if(res.data.code == 0 && res.data.message == "成功"){
        console.log(res.data.data.attention);
        this.setData({
          attention: res.data.data.attention,
        })
      }
    }).catch(err=>{
      console.warn(err);
    })

    let p1 = this.getLocationPromise();
    let p2 = this.getInfoPromise(options.tid);
    Promise.all([p1, p2]).then(values => {
      console.log(values);
      let _lat1 = values[0].latitude;
      let _lng1 = values[0].longitude;
      let _lat2 = values[1].data.data.latitude;
      let _lng2 = values[1].data.data.longitude;
      let distanceNum = this.getDistance(_lat1, _lng1, _lat2, _lng2);
      console.log(distanceNum);
      this.setData({
        distance: (distanceNum / 1000).toFixed(1),
        lat2: _lat2,
        lng2: _lng2,
        drivingSchoolName: values[1].data.data.name,
        grade: values[1].data.data.schoolLevel,
        briefIntroduction: [values[1].data.data.briefIntroduction.trim()],
        address: values[1].data.data.address,
        titlePic: values[1].data.data.titlePic,
        topPic: values[1].data.data.topPic,
        schoolName: values[1].data.data.schoolName,
        // classesList: values[1].data.data.classesList,
        headSchoolId: values[1].data.data.schoolId,
        totalPicsLength: values[1].data.data.pics.length,
        pics: values[1].data.data.pics,
      })
    });
    wx.getSystemInfo({
      success: (result) => {
        console.log(result.windowHeight);
        this.setData({
          scrollHeight: result.windowHeight
        });
      },
      fail: () => { },
      complete: () => { }
    });
    // wx.request({
    //   url: 'https://www.haitunxueche.com/student/index/getSchoolAreaVo',
    //   data:{
    //     areaId: options.tid,
    //   },
    //   header: {
    //     Authorization: getApp().globalData.login.token,
    //   },
    //   method: 'GET',
    //   dataType: 'json',
    //   success:(result)=>{
    //     console.log(result);
    //     console.log(result.statusCode);
    //     if (result.data.code == 0 && result.data.message == '成功'){
    //       this.setData({
    //         drivingSchoolName: result.data.data.name,
    //         grade: result.data.data.schoolLevel,
    //         briefIntroduction: result.data.data.briefIntroduction.trim(),
    //         address: result.data.data.address,
    //         titlePic: result.data.data.titlePic,
    //         topPic: result.data.data.topPic,
    //         schoolName: result.data.data.schoolName,
    //         classesList: result.data.data.classesList,
    //         headSchoolId: result.data.data.schoolId,
    //         totalPicsLength: result.data.data.pics.length,
    //         pics: result.data.data.pics,
    //       })
    //     }
    //   },
    //   fails:(res)=>{
    //     console.log(res);
    //   },
    //   complete:()=>{}
    // });
    //获取评价评分
    this.getAverageScore(options.tid).then(res => {
      console.log(res);
      if (res.data.code == 0 && res.data.message == "成功") {
        let _badRate = Math.round((res.data.data.badRate) * 100);
        let _goodRate = Math.round((res.data.data.goodRate) * 100);
        let _midRate = Math.round((res.data.data.midRate) * 100);
        let _score = Math.round(res.data.data.score).toFixed(1);
        let _score1 = Math.round(res.data.data.score);
        let _allTotal = res.data.data.total;
        let _goodTotal = res.data.data.goodCount;
        let _middleTotal = res.data.data.midCount;
        let _lowTotal = res.data.data.badCount;
        this.setData({
          badRate: _badRate,
          goodRate: _goodRate,
          midRate: _midRate,
          allTotal: _allTotal,
          goodTotal: _goodTotal,
          middleTotal: _middleTotal,
          lowTotal: _lowTotal,
          total: res.data.data.total,
          score: _score,
          score1: _score1 + ".0",
        })
        //重置评论数组内容
        this.resetFn(_allTotal, _goodTotal, _middleTotal, _lowTotal);
      }
    }).catch(err => {
      console.warn(err);
    });
    //评价
    this.getEvaluatePromise(1, 10, options.tid, 'ALL').then(res=>{
      console.info(res);
      if (res.data.code == 0 && res.data.message == "成功") {
        const _allArr = res.data.data.records;
        let _allArr1 = [];
        for (let i of _allArr) {
          let o = Object.assign({}, i);
          o.time = this.timestampToTime(i.createDate).split(' ')[0].split('-').join('.');
          _allArr1.push(o);
        }
        this.setData({
          allArr: _allArr1,
          allTotal: res.data.data.records.length,
        })
      }
    }).catch(err=>{
      console.warn(err);
    })
  },

  getAttentionPromise(optionsId){
    return new Promise((resolve,reject)=>{
      wx.request({
        url: 'https://www.haitunxueche.com/student/index/attention',
        data: {
          id: optionsId,
          type: 'SCHOOL',
        },
        header: {
          Authorization: getApp().globalData.login.token,
        },
        method: 'GET',
        dataType: 'json',
        success: (res) => {
          console.log(res);
          resolve(res);
        },
        fail: (error) => {
          reject(error);
        },
        complete: (res) => {

        }
      });
    })
  },

  getLocationPromise() {
    return new Promise((resolve, reject) => {
      wx.getLocation({
        type: 'gcj02',
        success: (res) => {
          resolve(res)
        }
      })
    })
  },

  getInfoPromise(paramsId) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'https://www.haitunxueche.com/student/index/getSchoolAreaVo',
        data: {
          areaId: paramsId,
        },
        header: {
          Authorization: getApp().globalData.login.token,
        },
        method: 'GET',
        dataType: 'json',
        success: (res) => {
          resolve(res);
        },
        fail: (err) => {
          reject(err);
        }
      })
    })
  },
  //计算距离
  getDistance: function (lat1, lng1, lat2, lng2) {
    lat1 = lat1 || 0;
    lng1 = lng1 || 0;
    lat2 = lat2 || 0;
    lng2 = lng2 || 0;
    var rad1 = lat1 * Math.PI / 180.0;
    var rad2 = lat2 * Math.PI / 180.0;
    var a = rad1 - rad2;
    var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
    var r = 6378137;
    return (r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2), 2)))).toFixed(0)
  },
  onReady: function () {

  },
  //点击tab切换
  swichNav(res) {
    if (this.data.currentType == res.detail.current) return;
    this.setData({
      currentType: res.detail.currentNum,
    })
    //全部
    if (res.detail.currentNum == 0) {
      this.getEvaluatePromise(1, 10, this.data.schoolId, 'ALL').then(res => {
        console.log(res);
        if (res.data.code == 0 && res.data.message == "成功") {
          const _allArr = res.data.data.records;
          let _allArr1 = [];
          for (let i of _allArr) {
            let o = Object.assign({}, i);
            o.time = this.timestampToTime(i.createDate).split(' ')[0].split('-').join('.');
            _allArr1.push(o);
          }
          this.setData({
            allArr: _allArr1,
            allTotal: res.data.data.records.length,
          })
        }
      }).catch(err => {
        console.warn(err);
      });
    }
    //好
    if (res.detail.currentNum == 1) {
      this.getEvaluatePromise(1, 10, this.data.schoolId, 'GOOD').then(res => {
        console.log(res);
        if (res.data.code == 0 && res.data.message == "成功") {
          const _allArr = res.data.data.records;
          let _allArr1 = [];
          for (let i of _allArr) {
            let o = Object.assign({}, i);
            o.time = this.timestampToTime(i.createDate).split(' ')[0].split('-').join('.');
            _allArr1.push(o);
          }
          this.setData({
            goodArr: _allArr1,
          })
        }
      }).catch(err => {
        console.warn(err);
      });
    }
    //中
    if (res.detail.currentNum == 2) {
      this.getEvaluatePromise(1, 10, this.data.schoolId, 'MIDDLE').then(res => {
        console.log(res);
        if (res.data.code == 0 && res.data.message == "成功") {
          const _allArr = res.data.data.records;
          let _allArr1 = [];
          for (let i of _allArr) {
            let o = Object.assign({}, i);
            o.time = this.timestampToTime(i.createDate).split(' ')[0].split('-').join('.');
            _allArr1.push(o);
          }
          this.setData({
            middleArr: _allArr1,
          })
        }
      }).catch(err => {
        console.warn(err);
      });
    }
    //差
    if (res.detail.currentNum == 3) {
      this.getEvaluatePromise(1, 10, this.data.schoolId, 'LOW').then(res => {
        console.log(res);
        if (res.data.code == 0 && res.data.message == "成功") {
          const _allArr = res.data.data.records;
          let _allArr1 = [];
          for (let i of _allArr) {
            let o = Object.assign({}, i);
            o.time = this.timestampToTime(i.createDate).split(' ')[0].split('-').join('.');
            _allArr1.push(o);
          }
          this.setData({
            lowArr: _allArr1,
          })
        }
      }).catch(err => {
        console.warn(err);
      });
    }
  },
  scrollFunc(e) {
    // console.log(e);
    if (e.detail.scrollTop > 650) {
      this.setData({
        scrollTp: 650
      })
    } else {
      this.setData({
        scrollTp: 0
      })
    }

    if (e.detail.scrollTop > 1200) {
      this.setData({
        curNavId: 2,
      })
    } else {
      this.setData({
        curNavId: 1,
      })
    }
  },
  testModal() {
    this.setData({
      modalCtrl: 'show'
    })
  },
  onCloseEvent() {
    this.setData({
      modalCtrl: 'hidden'
    })
  },
  handleTraining(e){
    console.log(e);
    let _lat1 = e.currentTarget.dataset.lat;
    let _lng1 = e.currentTarget.dataset.lng;
    this.getMap(_lat1, _lng1);
  },
  testModal2(){
    wx.navigateTo({
      url: '../allCoach/allCoach?tid=' + this.data.schoolId,
    })
  },
  handleAttionSchool(e){
    console.log(e);
    console.log(this.data.schoolId);

    this.getAttentionPromise(this.data.schoolId).then(res=>{
      if(res.data.code == 0 && res.data.message == "成功"){
        this.setData({
          attention: res.data.data.attention,
        })
      }
    }).catch(err=>{
      console.warn(err);
    });
  },
  getAttentionState(_areaId){
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'https://www.haitunxueche.com/student/index/getFansVo',
        data: {
          id: _areaId,
          type: 'SCHOOL',
        },
        header: {
          Authorization: getApp().globalData.login.token,
        },
        method: 'GET',
        dataType: 'json',
        success: (res) => {
          console.log(res);
          resolve(res);
        },
        fail: (error) => {
          reject(error);
        },
        complete: (res) => {

        }
      });
    })
  },
  getPicsPromise(_tid) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'https://www.haitunxueche.com/student/index/getTeacherPicVo',
        data: {
          id: _tid,
        },
        header: {
          Authorization: getApp().globalData.login.token,
        },
        method: 'GET',
        dataType: 'json',
        success: (res) => {
          resolve(res);
        },
        fail: (error) => {
          reject(error);
        },
        complete: function () { }
      })
    })
  },
  //获取分校教练列表
  getBranchListPromise(_tid){
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'https://www.haitunxueche.com/student/index/listTeacherListVo',
        data: {
          id: _tid,
        },
        header: {
          Authorization: getApp().globalData.login.token,
        },
        method: 'GET',
        dataType: 'json',
        success: (res) => {
          resolve(res);
        },
        fail: (error) => {
          reject(error);
        },
        complete: function () { }
      })
    })
  },
  //获取教练学员列表
  getStudentListPromise(_page, _pageSize, _schoolAreaId) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'https://www.haitunxueche.com/student/index/pageSchoolStudentVo',
        data: {
          page: _page,
          pageSize: _pageSize,
          schoolAreaId: _schoolAreaId,
        },
        header: {
          Authorization: getApp().globalData.login.token,
        },
        method: 'GET',
        dataType: 'json',
        success: (res) => {
          resolve(res);
        },
        fail: (error) => {
          reject(error);
        },
        complete: function () { }

      })
    })
  },
  //选择老师
  handleTeacher(e){
    console.log(e);
    let tid = e.currentTarget.dataset.tid;
    wx.navigateTo({
      url: '../coach/coach?tid=' + tid,
    })
  },
  handlePic(e){
    let picArr = this.data.pics;
    wx.navigateTo({
      url: '../drivingSchoolPic/drivingSchoolPic?picArr=' + picArr,
    })
  },
  toWeb() {
    const str = '1072173617632022528';
    const time = '2018年12月11日 00:57:29';
    wx.navigateTo({
      url: '../articleReading/articleReading?id=' + str + '&time=' + time,
    })
  },
  switchTab(e) {
    console.log(e);
    this.setData({
      curNavId: e.currentTarget.dataset.id,
    });
    if (e.currentTarget.dataset.id == 2) {
      this.setData({
        scrollTop: 1300,
      })
    } else if (e.currentTarget.dataset.id == 1) {
      this.setData({
        scrollTop: 650,
      })
    }
  },
  //获取平均评分
  getAverageScore(_drivingSchoolId) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'https://www.haitunxueche.com/student/index/getSchoolEvaluateStatisticsVo',
        data: {
          id: _drivingSchoolId,
        },
        header: {
          Authorization: getApp().globalData.login.token,
        },
        method: 'GET',
        dataType: 'json',
        success: (res) => {
          resolve(res);
        },
        fail: (error) => {
          reject(error);
        },
        complete: function () { }

      })
    })
  },
  handleHeaderSchool(){
    wx.navigateTo({
      url: '../headerSchool/headerSchool?tid=' + this.data.headSchoolId,
    })
  },
  //重置评论数组内容
  resetEvaluateArr(_allTotal, _goodTotal, _middleTotal, _lowTotal) {
    let tabsList = [{
      "name": "全部",
      "count": _allTotal,
    }, {
      "name": "好评",
      "count": _goodTotal,
    }, {
      "name": "中评",
      "count": _middleTotal,
    }, {
      "name": "差评",
      "count": _lowTotal,
    }]

    return tabsList
  },
  resetFn(_allTotal, _goodTotal, _middleTotal, _lowTotal) {
    this.setData({
      slideTabsData: this.resetEvaluateArr(_allTotal, _goodTotal, _middleTotal, _lowTotal),
    })
  },
  timestampToTime(timestamp) {
    // var date = new Date(timestamp * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
    var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
    var h = date.getHours() + ':';
    var m = date.getMinutes() + ':';
    var s = date.getSeconds();
    return Y + M + D + h + m + s;
  },
  getMap(_lat, _lng) {
    wx.getLocation({
      type: 'gcj02', //返回可以用于wx.openLocation的经纬度
      success: (res) => {
        this.setData({
          latitude: res.latitude,
          longitude: res.longitude,
        });
        var myAmap = new QQMapWX({ key: 'HTQBZ-FN3WI-IIRG7-5JWI4-74OFZ-AYFFJ' });
        // 调用接口
        myAmap.reverseGeocoder({
          location: {
            latitude: _lat,
            longitude: _lng,
          },
          success: (res) => {
            console.log(res);
            if (res.status == 0) {
              let _address = res.result.address;
              wx.openLocation({
                latitude: _lat,
                longitude: _lng,
                scale: 15,
                name: _address,
              })
            }
          },
          fail: function (res) {
            console.log(res);
          },
          complete: function (res) {
            console.log(res);
          }
        });
      }
    })
  },
  //获取评价
  getEvaluatePromise(_page, _pageSize, _schoolId, _type) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'https://www.haitunxueche.com/student/index/pageSchoolEvaluateVo',
        data: {
          page: _page,
          pageSize: _pageSize,
          schoolId: _schoolId,
          type: _type,
        },
        header: {
          Authorization: getApp().globalData.login.token,
        },
        method: 'GET',
        dataType: 'json',
        success: (res) => {
          resolve(res);
        },
        fail: (error) => {
          reject(error);
        },
        complete: function () { }

      })
    })
  },
  cjwt() {
    wx.navigateTo({
      url: '../wenzhang/wenzhang?key=cjwt',
    })
  }
})